import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { SysUser } from './user';

@Injectable()
export class UserService {

    constructor(private httpClient: HttpClient) { }

    getUserList(user: any): Promise<any> {
        return new Promise((resolve, reject) => {
            this.httpClient.get('api/sys/user/list').subscribe((res: any) => {
                resolve(res);
            });
        }).catch(this.handleError);
    }

    saveUser(user: SysUser): Promise<any> {
        return new Promise((resolve, reject) => {
            this.httpClient.post('api/sys/user/save', JSON.stringify(user), {
                headers: { 'Content-Type': 'application/json' }
            }).subscribe((res: any) => {
                resolve(res);
            });
        }).catch(this.handleError);
    }

    deleteUser(userId: number): Promise<any> {
        return new Promise((resolve, reject) => {
            this.httpClient.post('api/sys/user/delete/'+userId, {}).subscribe((res: any) => {
                resolve(res);
            });
        }).catch(this.handleError);
    }

    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error); // for demo purposes only
        return Promise.reject(error.message || error);
    }
}

